package com.wanlian.dao.impl;

import com.wanlian.common.PageCondition;
import com.wanlian.dao.ConfigDao;
import com.wanlian.entity.Config;
import com.wanlian.model.ResultModel;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class ConfigDaoImpl extends GenericDaoImpl<Config> implements ConfigDao {

    public ConfigDaoImpl() {
        super(Config.class);
    }

    @Override
    public ResultModel queryConfigList(PageCondition pageCondition) {
        ResultModel resultModel = new ResultModel();
        resultModel.setBresult(true);
        StringBuffer sqlWhere = new StringBuffer(" where 1 = 1");
        ArrayList<Object> params = new ArrayList<Object>();

        if(pageCondition.isEmpty("id")){
            int id=Integer.parseInt(pageCondition.getByKey("id")+"");
            sqlWhere.append(" and id= ?");
            params.add(id);
        }

        if(pageCondition.isEmpty("name")){
            String name= pageCondition.getByKey("name")+"";
            sqlWhere.append(" and name like ?");
            params.add("%"+name+"%");
        }

        if(pageCondition.isEmpty("ckey")){
            String ckey= pageCondition.getByKey("ckey")+"";
            sqlWhere.append(" and ckey like ?");
            params.add("%"+ckey+"%");
        }

        if(pageCondition.isEmpty("cvalue")){
            String cvalue= pageCondition.getByKey("cvalue")+"";
            sqlWhere.append(" and cvalue like  ?");
            params.add("%"+cvalue+"%");
        }

        List<Config> lists = new ArrayList<Config>();
        String hql = String.format(" from %s  ", entityClassName(),sqlWhere.toString());
        lists = this.queryForListByPage(hql+sqlWhere, params.toArray(), pageCondition.getPage());
        resultModel.setObject(lists);
        String countHql = String.format("select count(*) from  %s "+ sqlWhere, entityClassName(),params.toString());
        Long count = this.queryCount(countHql, params.toArray());
        resultModel.setCount(count);
        return resultModel;
    }

    public  Config queryById(int  id){
        String hql = String.format("from %s where id=? ", entityClassName());
        Config config = this.queryForObject(hql, new Object[]{id});
        return config;
    }

    public  Config queryByKey(String  key){
        String hql = String.format("from %s where ckey=? ", entityClassName());
        Config config = this.queryForObject(hql, new Object[]{key});
        return config;
    }

}
